<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use Zizaco\Entrust\EntrustPermission;

/**
 * Class Permission.
 *
 * @package namespace App\Models\Admin;
 */
class Permission extends EntrustPermission implements Transformable
{
    use TransformableTrait;

    protected $appends = ['sub_permission'];
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];

    public function getNameAttribute($value)
    {
        if (starts_with($value, '#')) {
            return head(explode('-', $value));
        }
        return $value;
    }

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = ($value === '#') ? '#-' . time() : $value;
    }

    public function getSubPermissionAttribute()
    {
        return ($this->attributes['fid'] == 0) ? $this->where('fid', $this->attributes['id'])->orderBy('sort')->orderBy('id', 'desc')->get() : null;
    }
}
